package com.share.rmi;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.share.Mbean.HelloMBean;

/**
 * 客户端Client程序，用于与agent进行远程连接：
 *
 */
public class HelloRMIClient
{
	public static void main(String[] args) throws IOException, Exception, NullPointerException
	{
		//建立链接
		String urlString = "service:jmx:rmi://localhost:9999/jndi/rmi://localhost:9999/jmxDefault";
		JMXServiceURL url = new JMXServiceURL(urlString);
		JMXConnector jmxc = JMXConnectorFactory.connect(url,null);
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

		//ObjectName:需要操作的MBean名
		ObjectName mbeanName = new ObjectName("jmxstudy:name=hello");
		//设置指定Mbean的特定属性值
		mbsc.setAttribute(mbeanName, new Attribute("Name","travleksy"));

		System.out.println("HelloRMIClient start...");

		System.out.println("call printHello()...");
		TimeUnit.SECONDS.sleep(3);
		//调用MBean函数:动态代理方式
		HelloMBean proxy = MBeanServerInvocationHandler.
				newProxyInstance(mbsc, mbeanName, HelloMBean.class, false);
		proxy.printHello("sunxj");

		System.out.println("call queryStatus()...");
		TimeUnit.SECONDS.sleep(3);
		//调用MBean函数:反射方式       
		mbsc.invoke(mbeanName, "queryStatus", null,null);
	}
}
